/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
var updtime;
FeedGrid = function(viewer, config) {
    this.viewer = viewer;
    Ext.apply(this, config);
    this.store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'feed-proxy.php'
        }),
		//url: 'feed-proxy.php',
/*         reader: new Ext.data.XmlReader(
            {record: 'item'},
            ['title', 'author', {name:'pubDate', type:'date'}, 'link', 'description', 'content','hasread']
        ) */
		
		reader: new Ext.data.JsonReader(
            {root: "rss.channel.item",id:"link"},
            ['title', 'author', {name:'pubDate', type:'date'}, 'link', 'description', 'content','hasread']
        )
    });
    this.store.setDefaultSort('pubDate', "DESC");

    this.columns = [{
        id: 'title',
        header: "Заголовок",
        dataIndex: 'title',
        sortable:true,
        width: 420,
		cont: "123",
        renderer: this.formatTitle
      },{
        header: "Автор",
        dataIndex: 'author',
        width: 100,
        hidden: true,
        sortable:true
      },{
        id: 'last',
        header: "Дата",
        dataIndex: 'pubDate',
        width: 150,
        renderer:  this.formatDate,
        sortable:true
    }];

	var cp = new Ext.state.CookieProvider();
	var sen = cp.get("sen",false);
	this.showPreview=false;
    FeedGrid.superclass.constructor.call(this, {
        region: 'center',
        id: 'topic-grid',
        loadMask: {msg:'Получение данных...'},

        sm: new Ext.grid.RowSelectionModel({
            singleSelect:true
        }),

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:this.showPreview,
			selRow: -1,
            getRowClass : this.applyRowClass
        }
    });
    //this.on('rowcontextmenu', this.onContextClick, this);
	this.on('rowclick',this.rowPreview,this);
	this.on('rowdblclick',this.rowPreview,this);
};

Ext.extend(FeedGrid, Ext.grid.GridPanel, {

    onContextClick : function(grid, index, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'grid-ctx',
                items: [{
                    text: 'Просмотр',
                    iconCls: 'new-tab',
                    scope:this,
                    handler: function(){
                        this.viewer.openTab(this.ctxRecord);
                    }
                },
				{
                    text: 'Открыть источник',
                    iconCls: 'new-tab',
                    scope:this,
                    handler: function(){
                        this.viewer.openTabIframe(this.ctxRecord);
                    }
                }
				
				,{
                    iconCls: 'new-win',
                    text: 'Открыть в новом окне',
                    scope:this,
                    handler: function(){
                        window.open(this.ctxRecord.data.link);
                    }
                },'-',{
                    iconCls: 'refresh-icon',
                    text:'Обновить',
                    scope:this,
                    handler: function(){
                        this.ctxRow = null;
                        this.store.reload();
                    }
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
        this.ctxRow = this.view.getRow(index);
        this.ctxRecord = this.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },

    loadFeed : function(url) {
        this.store.baseParams = {
            feed: url
        };
		var ftimes = Ext.util.JSON.decode(new Ext.state.CookieProvider().get("feedviewtimes","{}"));
		updtime = parseInt(ftimes[url]);
		this.view.selRow=-1;
        this.store.load();
		//this.show();
		//this.store.reload();
    },
	
	RefreshFeed : function(url) {
		var ftimes = Ext.util.JSON.decode(new Ext.state.CookieProvider().get("feedviewtimes","{}"));
		updtime = parseInt(ftimes[url]);
        this.store.reload();
    },

    togglePreview : function(show){
        this.view.showPreview = show;
        this.view.refresh();
		var cp = new Ext.state.CookieProvider();
		var sen = cp.get("sen",false);
		cp.set("sen",show);
    },

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
		//if (record.data.rowsel && this.showPreview) {
		var notime = (new Date(record.data.pubDate)).getTime();
				notime = parseInt(notime.toString().substring(0,notime.toString().length-3));
		var contentId = Ext.id();		
		var contentId2 = Ext.id();		
		var bbar = '<p><table><tr><td id="' + contentId + '"></td><td id='+contentId2+'></td></tr></table></p>';
		
		FeedViewer.getMainPanel.createButton.defer(1, this, ["Открыть источник", contentId, {type:1},record]);
		FeedViewer.getMainPanel.createButton.defer(1, this, ["Открыть источник в новом окне", contentId2, {type:2},record]);
		p.body = '<p id="rid_'+rowIndex+'">' + record.data.description + bbar+'</p>';
        if (rowIndex == this.selRow && !this.showPreview && false) {
            var xf = Ext.util.Format;
            //p.body = '<p>' + xf.ellipsis(xf.stripTags(record.data.description), 200) + '</p>';
			var hasread = record.data.hasread;
			if ((!updtime || notime>updtime) && !record.data.hasread) {
				return ('x-grid3-row-expanded newspreview ');
			}else{
				return ('x-grid3-row-expanded newspreview readed');
			}
        }
		return ('x-grid3-row-collapsed previewnone');
    },
	ButtonRender : function(value, metaData, record, rowIndex, colIndex, store) {
        this.createButton = function (value, contentid, attrs) {
            new Ext.Button({text: attrs.btext || "Кнопка", handler : function(btn, e) {
                        alert("Button");
                    }}).render(document.body, contentid);
        }
        
        this.createButton.defer(1, this, [value, contentId, attrs]);
        return('<div style="padding:0px;" id="' + contentId + '"></div>');
    },

    formatDate : function(date) {
        if (!date) {
            return '';
        }
		Date.dayNames =new Array ('Воскресенье','Понедельние','Вторник','Среда','Четверг','Пятница','Суббота');
		Date.monthNames =new Array ('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return 'Сегодня ' + date.dateFormat('G:i');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D G:i');
        }
        return date.dateFormat('n/j G:i');
    },

    formatTitle: function(value, p, record) {
		if (record.data.rowsel) {
			return String.format(
					'<div class="topic"><h3>{0}</h3></div>',
					value, record.data.author, record.id, record.data.forumid
					);
		}else{
			var notime = (new Date(record.data.pubDate)).getTime();
				notime = parseInt(notime.toString().substring(0,notime.toString().length-3));
				//value = UTF8.encode(value);
			if ((!updtime || notime>updtime) && !record.data.hasread) {
			return String.format(
					'<div class="topic"><b>{0}</b><span class="author">{1}</span></div>',
					value, record.data.author, record.id, record.data.forumid
					);
			}else{ 
				return String.format(
					'<div class="topic">{0}<span class="author">{1}</span></div>',
					value, record.data.author, record.id, record.data.forumid
					);
			}		
		}
    },
	rowPreview : function (grid, index, e) {
		var row = grid.getView().getRow(index);
		if (this.view.selRow>=0) {
			var prevrow = grid.getView().getRow(this.view.selRow);
			prevrow.className = prevrow.className.replace(" newspreview x-grid3-row-expanded","");
		}
		if (row) {
			if (index==this.view.selRow) {
				row.className = row.className.replace(" newspreview x-grid3-row-expanded","");
				this.view.selRow=-1;
			}
			else {
				this.view.selRow=index;
				row.className +=" newspreview x-grid3-row-expanded";
				this.view.focusRow(index);
			}
			//alert("ROW SEL");
			//this.view.refresh();
		}
	}
});